package org.darack_application;

import java.util.*;

import android.app.*;
import android.app.AlertDialog.Builder;
import android.content.*;
import android.net.*;
import android.os.*;
import android.text.*;
import android.util.*;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.*;

public class ContactsDBListActivity extends ListActivity {

	private String searchKeyword;
	ArrayList<String> iden_num, name, phone, email, workarea, photo_url;
	List<Contact> contactsList;
	private static final int TYPE_ITEM = 0;
	private static final int TYPE_SEPARATOR = 1;
	int j = 0;

	public void onBackPressed() {
		Builder d = new AlertDialog.Builder(this);
		d.setMessage("정말 종료하시겠습니까?");
		d.setPositiveButton("예", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				// process전체 종료
				finish();
			}
		});
		d.setNegativeButton("아니요", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		d.show();
	} 
	
	private void setContactsList() throws Exception {

		contactsList = new ArrayList<Contact>();
		int i = 0;


		while (i < name.size()) {
			boolean isheader = false;
			if(i==0||!(contactsList.get(j-1).getIden_num().equals(iden_num.get(i)))){
				if(i>0&&contactsList.get(j-1).isHeader()){
					contactsList.remove(j-1);
					j--;
				}
				isheader = true;
				addSeperator(contactsList, isheader,iden_num.get(i));
				j++;
			}

			addContact(contactsList, iden_num.get(i), name.get(i), phone.get(i), email.get(i), workarea.get(i),	R.drawable.contact_img);

			i++;
		}
		if(contactsList.get(j-1).isHeader())
			contactsList.remove(j-1);
	}

	private void addContact(List<Contact> contactsList, String iden_num, String name, String phone, String email, String workarea, int aIcon) throws Exception {

		if (contactsList == null) {
			throw new NullPointerException("contactList가 null 입니다.");
		}

		boolean isAdd = false;

		if (searchKeyword != null && "".equals(searchKeyword.trim()) == false) {

			String iniName = HangulUtils.getHangulInitialSound(name, searchKeyword);

			if (iniName.indexOf(searchKeyword) >= 0) {
				isAdd = true;
			}
		} 

		else {
			isAdd = true;
		}

		if (isAdd) {
			contactsList.add(new Contact(iden_num, name, phone, email, workarea, aIcon));
			j++;
		}
	}

	private void addSeperator(List<Contact> contactsList, boolean header, String iden_num) {
		contactsList.add(new Contact(header,iden_num));
	}

	private void displayList() throws Exception {

		List<Contact> contactsList = null;

		setContactsList();
		contactsList = this.contactsList;

		ContactsListAdapter<Contact> adapter = new ContactsListAdapter<Contact>(this, R.layout.activity_contact, contactsList);
		setListAdapter(adapter);
		j=0;
	}

	private class ContactsListAdapter<T extends Contact> extends
	ArrayAdapter<T> {

		private List<T> contactsList;

		public ContactsListAdapter(Context context, int textViewResourceId,
				List<T> items) {
			super(context, textViewResourceId, items);
			contactsList = items;
		}
		

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = null ;
			T contacts = contactsList.get(position);
			int isSelect = 0;
			

			LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			if (contacts.isHeader)
				isSelect = 1;

			switch (isSelect) {

			case TYPE_SEPARATOR:
				view = vi.inflate(R.layout.separator, null);

				TextView viewHeader = (TextView) view.findViewById(R.id.header);
				viewHeader.setFocusable(false);
				viewHeader.setTag(position);
				viewHeader.setOnClickListener(new OnClickListener(){
					public void onClick(View v){

					}
				});
				viewHeader.setOnTouchListener(new OnTouchListener() {

					public boolean onTouch(View v, MotionEvent e) {
						return false;
					}
				});
				viewHeader.setText(contacts.getIden_num());

				return view;

			case TYPE_ITEM:
				view = vi.inflate(R.layout.activity_contact, null);

				TextView viewName = (TextView) view.findViewById(R.id.toptext);
				viewName.setText(contacts.getName());				

				final Button call_bt = (Button) view.findViewById(R.id.callbtn);
				call_bt.setFocusable(false);
				call_bt.setTag(position);
				call_bt.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						int position = Integer.parseInt((v.getTag().toString()));
						Contact dump;
						dump = contactsList.get(position);
						Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + dump.getPhone()));
						startActivity(intent);
					}

				});
				call_bt.setOnTouchListener(new OnTouchListener() {

					public boolean onTouch(View v, MotionEvent e) {
						switch (e.getAction()) {
						case MotionEvent.ACTION_DOWN:
							call_bt.setBackgroundResource(R.drawable.phone2);
							break;
						case MotionEvent.ACTION_UP:
							call_bt.setBackgroundResource(R.drawable.phone1);
							break;
						}
						return false;
					}
				});
				final Button messagebtn = (Button) view.findViewById(R.id.messagebtn);
				messagebtn.setFocusable(false);
				messagebtn.setTag(position);
				messagebtn.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						int position = Integer.parseInt((v.getTag().toString()));
						Contact dump;
						dump = contactsList.get(position);
						Intent intent = new Intent(ContactsDBListActivity.this, SmsSender.class);
						intent.putExtra("phone", dump.getPhone());
						startActivity(intent);
					}

				});
				return view;
			}
			return view;			
		}
	}

	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent intent = new Intent(this, ContactdetailActivity.class);
		intent.putExtra("imageID", R.drawable.contact_img);
		
		Contact dump;
		dump = contactsList.get(position);
		intent.putExtra("iden_num", dump.getIden_num());
		intent.putExtra("name", dump.getName());
		intent.putExtra("phone", dump.getPhone());
		intent.putExtra("email", dump.getEmail());
		intent.putExtra("workarea", dump.getWorkarea());
		startActivity(intent);
	}

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list);
		iden_num = new ArrayList<String>();
		name = new ArrayList<String>();
		phone = new ArrayList<String>();
		email = new ArrayList<String>();
		workarea = new ArrayList<String>();
		photo_url = new ArrayList<String>();

		MThread mt = new MThread(iden_num, name, phone, email, workarea);
		mt.start();

		try {
			mt.join();
		} catch (Exception e) {

		}
		

		EditText searchBox = (EditText) findViewById(R.id.search);

		try {
			searchBox.addTextChangedListener(new TextWatcher() {

				public void afterTextChanged(Editable arg0) {
					// ignore
				}

				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
					// ignore
				}

				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					try {
						searchKeyword = s.toString();
						displayList();
					} catch (Exception e) {
						Log.e("", e.getMessage(), e);
					}
				}
			});

			displayList();
		} catch (Exception e) {
			Log.e("", e.getMessage(), e);
		}	
	}	
}
